<?php

App::import(array('Security', 'Sanitize', 'String'));

class UsersController extends AppController {
    var $name = 'Users';
    var $components = array('Email','Image');
    
    
    //var $uses = array('User','UserRegistration');
    
    /**
    * Allow unregistered/guest user for this component
    * 
    */
    function beforeFilter() {
        parent::beforeFilter(); 
        //$this->Auth->allow('*');
    }
    
    function login() {
        
        if(!empty($this->params['url']['referer']))
            $this->Session->write('redirect','/'.str_replace('.','#',$this->params['url']['referer']));
        
        
            
        
        
        
        if(!(empty($this->data)) && $this->Auth->user()) :
            $this->User->unBindModel(array('belongsTo' => array('Group')));
            $this->User->updateAll(array(
                    'last_login' => "'".date('Y-m-d H:i:s')."'",
                    'ip' => "'".$this->RequestHandler->getClientIP()."'",
                ),
                array(
                    'id' => $this->Auth->user('id')
                )
            );
            $this->Session->setFlash('You are logged in!');
            
            if($this->Session->read('redirect')):
                $redirect=$this->Session->read('redirect');
                $this->Session->write('redirect',null);
                $this->redirect($redirect);
            
            else :
                $ref = env('HTTP_REFERER');
                if($this->referer() == '/login') :
                    $this->redirect('/');
                else :
                    $this->redirect($this->referer());
                endif;
            endif;
            
            exit;
        endif;
    }
    
    function admin_login() {
        
         // setting the login page title
         
        $this->set('title_for_layout',$this->site_title.' :: Login');
        
        if(!(empty($this->data)))
            $this->set('error',true);
        if(!(empty($this->data)) && $this->Auth->user()) :
            $this->User->unBindModel(array('belongsTo' => array('Group')));
            $this->User->updateAll(array(
                    'last_login' => "'".date('Y-m-d H:i:s')."'",
                    'ip' => "'".$this->RequestHandler->getClientIP()."'",
                ),
                array(
                    'id' => $this->Auth->user('id')
                )
            );
            $this->Session->setFlash('You are logged in!');
            
            $group =&$this->User->Group;
            
            $group->id = $this->Auth->user('group_id');
            
            Cache::delete('admin_menu-'.$group->id, 'default');
            
            if(!$this->Acl->check($group,'controllers/Dashboards/admin_index'))
                $this->redirect('/');
            
            $ref = env('HTTP_REFERER');
                if($this->referer() == '/login') :
                    $this->redirect(array('controller' => 'dashboards', 'action' => 'index', 'admin' => true));
                else :
                    $this->redirect($this->referer());
                endif;
            exit;
        elseif($this->Auth->user()):
            $this->redirect(array('controller' => 'dashboards', 'action' => 'index', 'admin' => true));
            exit;
        endif;
        
    }
    
    function logout() {
        $this->User->unBindModel(array('belongsTo' => array('Group')));
        $this->User->updateAll(array('last_login'=>'"'.date('Y-m-d H:i:s').'"'),array('id'=>$this->Auth->user('id')));
        $this->Session->setFlash('Good-Bye');
        $this->Auth->logout();
        $this->redirect('/');
        exit;
    }
    
    function admin_logout() {
        $this->User->unBindModel(array('belongsTo' => array('Group')));
        $this->User->updateAll(array('last_login'=>'"'.date('Y-m-d H:i:s').'"'),array('id'=>$this->Auth->user('id')));
        $this->Session->write('Success',true);
        $this->Session->setFlash('Good Bye!');
        $this->Auth->logout();
        $this->redirect('/cp');
        exit;
    }
    
    
    
    function recover() {
        if(!empty($this->data)) :
            $email = $this->data['User']['email'];
            $newPass = trim(substr(md5(uniqid(mt_rand(), true)), 0, 8));
            
            $this->User->recursive = -1;
            $user = $this->User->find('first', array('conditions' => array('User.email' => $email)));
            if(!empty($user)) :
                $user['User']['password'] = md5($newPass);
                
                if($this->User->save($user, false)) :
                    // send email using the Email component
                    $this->Email->to = $email;
                    if(env('REMOTE_ADDR') == '127.0.0.1') $this->Email->to = 'jitu@localhost';
                    $this->Email->subject = 'Bangladesh Yellow Pages User Account';
                    $this->Email->from = '"Bangladesh Yellow Pages" <no-reply@bangladeshyellowpages.com>';
                    $this->Email->template = 'recover';
                    
                    $this->set('password', $newPass);
                    $this->set('email', $email);
                    $this->set('username', $user['User']['username']);
                    
                    //$this->Email->_debug = true;
                    $this->Email->send();
                    $this->Session->write('Success',true);
                    $this->Session->setFlash('Please check your mail for new password');
                    endif;
            else :
                $this->Session->setFlash('No email address matched');
            endif;
            
        endif;
        $this->redirect($this->referer());
        exit;
    }
     
    
    
    
    /**
    * Admin Section Starts form here
    * Be Carefull :D
    */    
    function admin_public($type = null) {
        if($type==null)
            $type='active';
        
        $types = array('active', 'hold', 'banned');
        $options = array();
        if($type && in_array($type, $types)) :
            $options = array(
                'User.status' => $type,
                
            );
            if($type=='banned') :
                $options = array('OR' => array('User.status' => 'banned'));
            endif;
        else :
            $options = array(
                'User.status <>' => 'inactive'
            );
        endif;
        
        $options['User.group_id']=3;//public
        
        
        if(isset($this->passedArgs['term']) || ( !empty($this->data) && isset($this->data['Search']) ) ) :
            if(isset($this->passedArgs['term'])) :
                $this->data['Search']['term'] = $this->passedArgs['term'];
            endif;
            $options = am($options, array('User.name LIKE' => '%'.$this->data['Search']['term'].'%'));
            $this->passedArgs = am($this->passedArgs, array('term' => $this->data['Search']['term']));
        endif;
        
        //$user = array('Comment.post_user_id' => $this->Auth->user('id'));
        //$options = am($user, $options);
        $this->paginate['User'] = array(
            'discardJoins' => true,
            'order' => array('User.created' => 'DESC'),
        );
        
        $users = $this->paginate('User', $options);
        $this->set(compact('users'));
        
        $this->set('type', $type);
        
        $this->User->recursive = -1;
        $active = $this->User->find('count', array('conditions' => array('User.status' => 'active','User.group_id'=>3)));
        $this->set('count_active', $active);
        $banned = $this->User->find('count', array('conditions' => array('User.status' => 'banned','User.group_id'=>3)));
        $this->set('count_banned', $banned);
        $hold = $this->User->find('count', array('conditions' => array('User.status' => 'hold','User.group_id'=>3)));
        $this->set('count_hold', $hold);
        //$this->set('count_all', $this->User->find('count', array('conditions' => am($user, array('NOT' => array('Comment.status' => 'deleted'))))));
        $this->set('count_all', $active+$banned+$hold);
    }
    
    
    
    function admin_index($type = null) {
        
        $options = array('User.group_id <>'=>3);// not public users
    
        $this->paginate['User'] = array(
            'discardJoins' => true,
            'order' => array('User.created' => 'DESC'),
        );
        
        $users = $this->paginate('User', $options);
        $this->set(compact('users'));
        

    }
    
    
    
    function admin_add() {
        
        if($this->Auth->user('group_id')!=1) :
            $this->Session->setFlash('Only a Superadmin can add an user!');
            $this->redirect($this->referer());
            exit;
        endif;
        
        $groups = $this->User->Group->find('list',array('conditions'=>array('id <>'=>1)));
        $this->set(compact('groups'));
        
        if(!empty($this->data)) :
            
            if($this->User->find(array('username'=>$this->data['User']['username']))){
                
                $this->Session->setFlash('Username Already Exists!, please try another name');
                
                $this->redirect($this->referer());
                exit;
                
            }
            
            
            // Clean
            foreach($this->data['User'] as $key => $item):
                if($key == 'details') $this->data['User'][$key] = strip_tags($item, '<a><img>');
                elseif(is_string($item)) $this->data['User'][$key] = htmlspecialchars($item, ENT_QUOTES);
            endforeach;
            
            
            
            // Prevent Validation Fail
            if($this->data['User']['passwd'] == '') :
                unset($this->data['User']['passwd']);
            else:
                $this->data['User']['passwd'] = $this->Auth->password($this->data['User']['passwd']);
                $this->data['User']['password'] = $this->data['User']['passwd'];
            endif;
            
            // prevent hack
            if($this->data['User']['group_id']==1)$this->data['User']['group_id']=2;
            
            
            
            
            if($this->User->save($this->data)) :
                $this->Session->write('Success',true);
                $this->Session->setFlash('User Created sucessfully');
                
                $this->redirect($this->referer());
                exit;
            endif;
        endif;
        
        
    }
    
    
    
    function admin_delete($id = null) {
        if($id == null) :
            $this->redirect($this->referer());
            exit;
        endif;
        $id = (int)$id;
        
        $user=$this->User->find('first',array('conditions'=>array('User.id'=>$id)));
        if($user['User']['group_id']==1){
            $this->Session->setFlash('A superadmin is not allowed to be deleted!');
            $this->redirect($this->referer());
            exit;
        }
        $this->User->unbindModel(array('belongsTo' => array('Group')));
        
        
        if($this->User->updateAll(array(
                    'status' => "'deleted'",
                ),
                array(
                    'id' => $id
                )
            )) :
            $this->Session->write('Success',true);
            $this->Session->setFlash('User Deleted sucessfully');
        endif;
        $this->redirect($this->referer());
        exit;
    }
    
    
    function admin_profile($userId = null) {
        if(!in_array($this->Auth->user('group_id'), array(1))) :
            $userId = $this->Auth->user('id');
        else :
            if($userId==null) $userId = $this->Auth->user('id');
        endif;
        
        $userId = (int)$userId;
        
        if(!empty($this->data)) :
            // prevent change the superadmin to other    
            $user=$this->User->find('first',array('conditions'=>array('User.id'=>$userId)));
            
            
            
            //group id
            $this->data['User']['group_id']=$user['Group']['id'];
            
            
            
            // Clean
            foreach($this->data['User'] as $key => $item):
                if($key == 'details') $this->data['User'][$key] = strip_tags($item, '<a><img>');
                elseif(is_string($item)) $this->data['User'][$key] = htmlspecialchars($item, ENT_QUOTES);
            endforeach;
            
            
            
            // Prevent Validation Fail
            if($this->data['User']['passwd'] == '') :
                unset($this->data['User']['passwd']);
            else:
                $this->data['User']['passwd'] = $this->Auth->password($this->data['User']['passwd']);
                $this->data['User']['password'] = $this->data['User']['passwd'];
            endif;
            
            
            
            $this->User->id = $userId;
            //$this->data['User']['id']=$userId;
            
            /*if($this->Auth->user('group_id')==1) :                */
                $blackList = array('email', 'username',  'duration', 'ip', 'last_login', 'created');
            /*else:
                $blackList = array('email', 'username',  'duration', 'ip', 'last_login', 'created','group_id');
            endif;*/
            
            
            
            $whiteList = array_diff(array_keys($this->User->schema()), $blackList);
            
            
            
            if($this->User->save($this->data, true, $whiteList)) :
                $this->Session->write('Success',true);
                $this->Session->setFlash('Profile updated sucessfully');
                
                if($userId == $this->Auth->user('id')) :
                    foreach($this->data['User'] as $key=>$value) $this->Session->write('Auth.User.'.$key,$value);
                endif;
                
                $this->redirect($this->referer());
                exit;
            endif;
        endif;
        
        
        
        $this->data = $this->User->find('first', array('conditions' => array('User.id' => $userId), 'contain' => false));
        
        
        
    }
    
    
    
    
    function admin_add_permission($aco_id=null,$group_id=null) {
        
        
        
        if($aco_id== null || $group_id==null){
            $this->redirect($this->referer());
        }
        if($group_id==1){
            $this->Session->setFlash('Superadmin is not allowed to modify!');   
            $this->redirect($this->referer());
        }
        
        $group =&$this->User->Group;
        $group->id = $group_id;     
        
        $aco=$this->Acl->Aco->find('first',array('conditions'=>array('id'=>$aco_id)));
        $aco_parent=$this->Acl->Aco->find('first',array('conditions'=>array('id'=>$aco['Aco']['parent_id'])));
        
        $this->Session->setFlash('Failed to update permission!');
        if($this->Acl->allow($group, 'controllers/'.$aco_parent['Aco']['alias'].'/'.$aco['Aco']['alias'])){
            $this->Session->write('Success',true);
            $this->Session->setFlash('Permission has been updated successfully!');
            Cache::delete('admin_menu-'.$group_id, 'default');
         
        }
        
        
        $this->redirect($this->referer());
        
        
        
    }
    
    function admin_remove_permission($aco_id=null,$group_id=null) {
        
        
        
        if($aco_id== null || $group_id==null){
            $this->redirect($this->referer());
        }
        if($group_id==1){
            $this->Session->setFlash('Superadmin is not allowed to modify!');   
            $this->redirect($this->referer());
        }
        
        $group =&$this->User->Group;
        $group->id = $group_id;     
        
        $aco=$this->Acl->Aco->find('first',array('conditions'=>array('id'=>$aco_id)));
        $aco_parent=$this->Acl->Aco->find('first',array('conditions'=>array('id'=>$aco['Aco']['parent_id'])));
        
        $this->Session->setFlash('Failed to update permission!');
        if($this->Acl->deny($group, 'controllers/'.$aco_parent['Aco']['alias'].'/'.$aco['Aco']['alias'])){
            $this->Session->write('Success',true);
            $this->Session->setFlash('Permission has been updated successfully!');
            Cache::delete('admin_menu-'.$group_id, 'default');
        }
        
        
        $this->redirect($this->referer());
        
        
        
    }
    
    
    function admin_permissions($id) {
        
        $group =& $this->User->Group;
        
        $group->id = 1;
        $this->Acl->allow($group, 'controllers');
        
        $conditions = array(
            'parent_id !=' => null,
            'model' => null,
            'foreign_key' => null,
            'alias !=' => null,
        );
        $acos  = $this->Acl->Aco->generatetreelist($conditions, '{n}.Aco.id', '{n}.Aco.alias');
        
        
        $groups = $this->User->Group->find('list',array('conditions'=>array('id'=>$id)));
        $this->set(compact('acos', 'groups'));
        
        $options = array(
            'conditions' => array(
                'Aro.model' => 'Group',
                'Aro.foreign_key' => array_keys($groups),
            ),
            'recursive' => -1,
        );
        $aros = $this->Acl->Aro->find('all', $options);
        $aros = Set::combine($aros, '{n}.Aro.foreign_key', '{n}.Aro.id');
        //debug($aros);
        
        $permissions = array(); // acoId => roleId => bool
        foreach ($acos as $acoId => $acoAlias) {
            if (substr_count($acoAlias, '_') != 0) {
                
                $permission = array();
                foreach ($groups AS $groupId => $groupTitle) {
                    $hasAny = array(
                        'aco_id'  => $acoId,
                        'aro_id'  => $aros[$groupId],
                        '_create' => 1,
                        '_read'   => 1,
                        '_update' => 1,
                        '_delete' => 1,
                    );
                    if ($this->Acl->Aro->Permission->hasAny($hasAny)) {
                        $permission[$groupId] = 1;
                    } else {
                        $permission[$groupId] = 0;
                    }
                    $permissions[$acoId] = $permission;
                }
            }
        }
        $this->set(compact('aros', 'permissions'));
    }
    
    
    
    
    function register() {
        if($this->Auth->user()){
            $this->redirect('/');
            exit;
        }
        if($this->data):
            // remove default values
            if($this->data['User']['location'] == 'অবস্থান') $this->data['User']['location'] = '';
            if($this->data['User']['name'] == 'নাম (বাংলায়)') $this->data['User']['name'] = '';
            //if($this->data['User']['details'] == 'বিস্তারিত') $this->data['User']['details'] = '';
            
            // 3 is for user, for details see groups table in database
            $this->data['User']['group_id'] = 3;
            $this->data['User']['status'] = 'inactive';
            $this->data['User']['activation_key'] = Security::hash(time(), 'sha256', 'lolzAitaSectect');
            
            unset($this->data['User']['fakepassword']);
            unset($this->data['User']['fakepasswd']);
            
            //$this->data['User']['password'] = $this->Auth->password($this->data['User']['password']);
            
            $orginalPass = $this->data['User']['passwd'];
            if(!empty($this->data['User']['passwd'])) $this->data['User']['passwd'] = $this->Auth->password($this->data['User']['passwd']);
            
            // $this->User->data = Sanitize::clean($this->data);
            $this->data = Sanitize::clean($this->data);
            
            //debug($this->data);
            
            if($this->User->save($this->data)) :
                // send email using the Email component
                $this->Email->to = $this->data['User']['email'];
                $this->Email->subject = 'Activate Your Bangladesh Yellow Pages Account';
                $this->Email->from = '"Bangladesh Yellow Pages" <no-reply@banfladeshyellowpages.com>';
                $this->Email->template = 'activate';
                
                $this->set('username', $this->data['User']['username']);
                $this->set('password', $orginalPass);
                $this->set('activation_key', $this->data['User']['activation_key']);
                $this->set('email', $this->data['User']['email']);
                
                //$this->Email->_debug = true;
                $this->Email->send();
                $this->Session->write('Success',true);
                $this->Session->setFlash('Please check your mail for the activation link');
                
                $this->redirect('/');
                exit;
            endif;
            
            unset($this->data['User']['password']);
            unset($this->data['User']['passwd']);
            
        endif;
    }
    
    
    function profile() {
        if(!$this->Auth->user()) {
            $this->redirect('/');
            exit;
        }
        
        $userId=$this->Auth->user('id');
        
        
        
        if(!empty($this->data)) :
            // prevent change the superadmin to other    
            $user=$this->User->find('first',array('conditions'=>array('User.id'=>$userId)));
            
            
            // Clean
            foreach($this->data['User'] as $key => $item):
                if($key == 'details') $this->data['User'][$key] = strip_tags($item, '<a><img>');
                elseif(is_string($item)) $this->data['User'][$key] = htmlspecialchars($item, ENT_QUOTES);
            endforeach;
            
            
            
            // Prevent Validation Fail
            if($this->data['User']['passwd'] == '') :
                unset($this->data['User']['passwd']);
            else:
                $this->data['User']['passwd'] = $this->Auth->password($this->data['User']['passwd']);
                $this->data['User']['password'] = $this->data['User']['passwd'];
            endif;
            
            
            
            $this->User->id = $userId;
            $this->data['User']['id']= $userId;
            
            
            //group id
            $this->data['User']['group_id']=$user['Group']['id'];
            
            
            if(!empty($this->data['User']['profile_image']['name'])) :
                //pr($this->data);
                $img = $this->Image->upload_image_and_thumbnail($this->data['User']['profile_image'], 220, 220, 'profile_pictures', 'resizeCrop', $this->Auth->user('username'));
                if($img) :
                    $this->data['User']['profile_image'] = $img ;
                else :
                    unset($this->data['User']['profile_image']);
                endif;
            else :
                unset($this->data['User']['profile_image']);
            endif;
            
            
            $blackList = array('email', 'username',  'duration', 'ip', 'last_login', 'created');
            
            
            $whiteList = array_diff(array_keys($this->User->schema()), $blackList);
            
            if($this->User->save($this->data, true, $whiteList)) :
                $this->Session->write('Success',true);
                $this->Session->setFlash('Profile updated sucessfully');
                
                if($userId == $this->Auth->user('id')) :
                    foreach($this->data['User'] as $key=>$value) $this->Session->write('Auth.User.'.$key,$value);
                endif;
                
                $this->redirect('/profile');
                exit;
            endif;
        endif;
        
        
        
            
        $username = $this->Auth->user('username');
        
        
        
        
        $options = array(
            'conditions' => array(
                'User.username' => $username,
                //'User.status' => 'active',
            ),
            
        );
        $this->data = $this->User->find('first', $options);
        
        unset($this->data['User']['password']);
        
        
        if(empty($this->data)) :
            $this->redirect('/');
            exit;
        endif;
        
        if($this->data['User']['status'] == 'banned') :
            $this->Session->setFlash("উক্ত ব্যবহারকারীকে ব্যান করা হয়েছে।");
            $this->redirect('/');
            exit;
        endif;
        
        
        //$this->pageTitle = ((isset($profile['User']['name']) ? $profile['User']['name'] : $profile['User']['username'])).' - '. $this->pageTitle;
        
        
        
        
        
        
    }
    
    
    /**
    * Registration Mail Activation
    */
    
    function activate($key) {
        $this->User->unbindModel(array('belongsTo' => array('Group')));
        
        if($this->User->updateAll(
            array(
                'activation_key' => NULL,
                //'status' => "'hold'",
                'status' => "'active'",
                'ip' => "'".$this->RequestHandler->getClientIP()."'",
            ),
            array(
                'activation_key' => $key
            )
        )) :
            
            $this->Session->write('Success',true);
            //$this->Session->setFlash('Your account has been activated & awaiting for moderation');
            $this->Session->setFlash('Your account has been activated. you can now add your business!');
        else :
            $this->Session->setFlash('This key has been expired');
        endif;
        
        //$this->redirect(array('controller' => 'users', 'action' => 'login'));
        $this->redirect('/');
        exit;
    }
    
    
    
     function admin_active($id) {
        if($id == null) :
            $this->redirect($this->referer());
            exit;
        endif;
        $this->User->unbindModel(array('belongsTo' => array('Group')));
        
        $options = array(
            'conditions' => array(
                'User.id' => $id,
                //'User.status' => 'active',
            )
        );
        $data = $this->User->find('first', $options);
        
        
        if($this->User->updateAll(array('User.status' => "'active'"), array('User.id' => $id))) :
            // send email using the Email component
            $this->Email->to = $data['User']['email'];
            
            $this->Email->subject = 'Your Bangladesh Yellow Pages Account has been activated by the Moderator';
            $this->Email->from = '"Bangladesh Yellow Pages" <no-reply@bangladeshyellowpages.com>';
            $this->Email->template = 'activated_by_moderator';
            
            $this->set('username', $data['User']['username']);
            $this->set('email', $data['User']['email']);
            //$this->Email->_debug = true;
            $this->Email->send();
            $this->Session->write('Success',true);
            $this->Session->setFlash('User has been activated sucessfully');
        endif;
        $this->redirect($this->referer());
        exit;
    }
    
    
    
    function admin_ban($id) {
        if($id == null) :
            $this->redirect($this->referer());
            exit;
        endif;
        $this->User->unbindModel(array('belongsTo' => array('Group')));
        
        if($this->User->updateAll(array('User.status' => "'banned'"), array('User.id' => $id))) :
            $this->Session->write('Success',true);
            $this->Session->setFlash('User has been banned sucessfully');
        endif;
        $this->redirect($this->referer());
        exit;
    }
    
    
    
    
}
?>
